<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- Bootstrap -->
    <link href="/bootstrap-3.4.1/css/bootstrap.css" rel="stylesheet">    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
    <!-- 选项 1：jQuery 和 Bootstrap 集成包（集成了 Popper） -->
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
    <script src="/bootstrap-3.4.1/js/jquery.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="/bootstrap-3.4.1/js/bootstrap.js"></script>
</head>
<style>
    *{
        padding: 0;
        margin: 0;
    }
    .chat-person{
        width: 200px;
        height: 650px;
        margin: auto;
        float: left;
        background-color: #e8e8e8;
        overflow: auto;
    }

    .chat-person .left-m{
        height: 70px;

    }
    .chat-person .left-m:hover{
        background-color: white;
    }

    .chat-person .left-m .left-d{
        width: 50px;
        height: 50px;
        background-color: #4459AB;
        float: left;
        margin-top: 10px;
        margin-left: 10px;
        margin-right: 10px;
        text-align: center;
        line-height: 50px;
        color: white;
        border-radius: 25px;
    }
    .active{
        background-color: white;
    }
    .chat-person .left-m .right-d{

        width: 110px;
        height: 100%;
        float: right;
        /*background-color: red;*/
        text-align: center;
    }
    .chat-person .left-m .right-d div{
        margin-top: 20px;
        margin-bottom: 10px;
    }

    .chat-person ul li:hover{
        background-color: green;
    }
    .chat_commento{
        width: 800px;
        height: 650px;
        margin: auto;
        border-radius: 10px;
        border: 2px solid #f4f5f7;
    }
    .clearfix::after{
        content: "";
        display: block;
        clear: both;
        width: 0;
        height: 0;
        line-height: 0;
        visibility: hidden;
    }
    /* top */
    .chat_top{
        height: 50px;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        padding-left: 20px;
        font-size: 20px;
        line-height: 50px;
        box-sizing: border-box;
        font-weight: 550;
        border-width: 0px;
    }
    /* middle */
    /* 左边 */
    .chat_middle{
        height: 455px;
        position: relative;
        box-sizing: border-box;
        overflow: auto;
        border-width: 0px;
    }
    .chat_left{
        width: 100%;
        height: 120px;
        margin-top: 20px;
    }
    .chat_left_item_1{
        width: 50px;
        height: 50px;
        background-color: #4459AB;
        float: left;
        margin-top: 10px;
        margin-left: 10px;
        margin-right: 10px;
        text-align: center;
        line-height: 50px;
        color: white;
        border-radius: 25px;
    }
    .chat_left_item_2{
        width: 55%;
        height: 100px;
        float: left;
        margin-top: 10px;
    }
    .chat_left_item_2 .chat_left_chat{
        float: left;
    }
    .chat_left_item_2 .chat_left_content{
        padding: 15px;
        margin-top: 10px;
        background-color: #f4f5f7;
        display: inline-block;
        border-radius: 10px;
        border-top-left-radius: 0px;
    }
    /* 右边 */
    .chat_right{
        width: 100%;
        height: 120px;
        margin-top: 20px;
    }
    .chat_right_item_1{
        width: 50px;
        height: 50px;
        background-color: #4459AB;
        float: right;
        margin-top: 10px;
        margin-left: 10px;
        margin-right: 10px;
        text-align: center;
        line-height: 50px;
        color: white;
        border-radius: 25px;
    }
    .chat_right_item_2{
        width: 55%;
        height: 100px;
        float: right;
        margin-top: 10px;
    }
    .chat_right_time{
        width: 100%;
        text-align: right;
    }
    .chat_right_content{
        float: right;
        padding: 15px;
        border-radius: 10px;
        margin-top: 10px;
        border-top-right-radius: 0px;
        background-color: #4F7cff;
        color: white;
    }
    /* foot */
    .chat_foot{
        height: 130px;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        position: relative;
        margin-left: 200px;
    }
    .chat_context{
        height: 100%;
        font-size: 17px;
        box-sizing: border-box;
        outline: none;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        border-width: 0px;
        padding: 16px;
    }
    .chat_commit{
        width: 180px;
        height: 30px;
        color: white;
        background-color: #4F7cff;
        line-height: 30px;
        text-align: center;
        border-radius: 5px;
        position: absolute;
        right: 10px;
        bottom: 20px;
        margin-right: 10px;
    }
    .chat_context{
        resize: none;
    }
    .chat_context::placeholder{
        color: black;
        font-weight: 500k;
    }
    .line{
        width: 100%;
        border-top: 1px;
        border-color: #f4f5f7;
        border-style: solid;
    }

    #add_person{
        background-color:#f66f6a;
        color:white;
        width: 45px;
        height: 45px;
        border:0;
        font-size: 16px;
        box-sizing: content-box;
        border-radius: 5px;
        margin-left: 10px;
    }
    #add_person:hover{
        background-color: #a54b4a;
    }

</style>
<body>

<div class="chat_commento" id="main" style="display: none;">

    <!-- entry -->
    <div  class="chat-person" id="sidler" >
        <div class="left-m" >
            <div class="left-d" >天乐</div>
            <div class="right-d">
                <div>192.168.188.100</div>
            </div>
        </div>
        <div class="left-m" >
            <div class="left-d" >哈哈</div>
            <div class="right-d">
                <div>192.168.188.100</div>
            </div>
        </div>
        <div class="left-m" >
            <div class="left-d" >客户</div>
            <div class="right-d">
                <div>192.168.188.100</div>
            </div>
        </div>
        <div class="left-m">
            <div class="left-d group" >群聊1</div>
            <div class="right-d">
                <div>192.168.188.100</div>
            </div>
        </div>
    </div>

    <!-- top -->
    <div class="chat_top" id="top">
        <div id="popUpBox">

        </div>
        <div id="top_left" style="float:left;">
            这是首页
        </div>
        <div id="top_middle" style="width: 45px;height:45px;margin-left: 10px;border-radius: 50px;text-align: center;float: left;background-color: aqua;">

        </div>
<!--        <div id="add_man" style="text-align: center;height:45px;font-size: 20px;float: left;margin-left: 10px;">-->
<!--            -->
<!--        </div>-->
        <button type="button" id="add_person" class="glyphicon glyphicon-plus" data-target="#myModal" ></button>
        <button type="button" id="refresh" class="glyphicon glyphicon-repeat btn-success" style="border: none;border-radius: 10px;height: 45px;width: 45px;margin-left: 10px;"  ></button>

        <div id="top_right" style="background-color: cornflowerblue;width: 45px;height: 45px;float: right;border-radius: 50px;text-align: center;">

        </div>
    </div>
<!--    模态框-->
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">添加好友</h4>
                </div>
                <div class="modal-body">
                    <form  role="search" id="friend">
                        <div class="form-group">
                            <label for="friendname">好友名称:</label>
                            <input type="text" name="friendName" id="friendname" class="form-control" placeholder="name">
                        </div>
                        <div class="form-group">
                            <label for="friendip">好友ip:</label>
                            <input type="text" name="friendIp" id="friendip" class="form-control" placeholder="password">
                        </div>
                        <div class="form-group">
                            <label for="status">选择类型</label>
                            <select class="form-control" name="status" id="status">
                                <option selected>好友</option>
                                <option >群聊</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" id="save" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>


    <!-- line -->
    <div class="line"></div>
    <!-- middle -->
    <div class="chat_middle" id="chat_middle_item">
        <!-- 左边 -->
        <div class="chat_left clearfix">
            <div class="chat_left_item_1 ">天乐</div>
            <div class="chat_left_item_2">
                <div class="chat_time">18:57</div>
                <div class="chat_left_content">
                    计算机网络课程实践难不难?
                </div>
            </div>
        </div>
        <!--右边 -->
        <div class="chat_right">
            <div class="chat_right_item_1 ">热巴</div>
            <div class="chat_right_item_2 ">
                <div class="chat_right_time">18:59</div>
                <div class="chat_right_content">
                    难吗?这不就做出来了!
                </div>
            </div>
        </div>
        <!-- l_2 -->
        <div class="chat_left clearfix">
            <div class="chat_left_item_1 ">天乐</div>
            <div class="chat_left_item_2">
                <div class="chat_time">18:57</div>
                <div class="chat_left_content">
                    别装了,先做出后台服务器再说吧!
                </div>
            </div>
        </div>
    </div>
    <!-- line -->
    <div class="line"></div>
    <!-- foot -->
    <div class="chat_foot">
        <!-- context -->
        <textarea class="chat_context" id="chat_context_item" cols="30" rows="10" placeholder="请输入"></textarea>
        <button type="button" class="chat_commit" onclick="SendData();" id="button">发送[ctrl+enter]</button>
    </div>
</div>
<div class="first" id="first" style="display: block;margin-left: 100px;" >
    <label for="username">用户名: </label>
    <input id="username" class="form-control" style="width: 400px;" name="username" type="text"/><br/>
    <button type="button" class="btn btn-success" onclick="first();">进入聊天室</button>

</div>
<script>
    var basePath="http://localhost:8080"
</script>
<script>
    <!--    JQuery-->
    $(document).on("click", "#add_person", function () {
        $("#myModal").modal('show');
    })

    /*
    * 添加好友
    * */

    $(document).on("click", "#save", function () {
        if ($("#status").val()==='群聊'){
            status=1;
        }else
            status=0;


        //只有在status==0的时候,才向对方发送确认,不然就是加入到群组里
        //只有对方同意添加后才添加
        if(status==="0"){
            alert("添加好友完毕,待对方同意...")
            var json11={}
            json11.message='add';
            json11.user=user;
            json11.uuid=$("#friendname").val();
            try {
                //向后台服务器发生消息
                ws.send(JSON.stringify(json11));
            } catch (ex) {
                alert(ex.message);
            }
        //    不然就直接加入到群组里
        }else {
            let data = {
                "mainName":user,
                "friendName":$("#friendname").val(),
                "friendIp":$("#friendip").val(),
                //当前的添加对象的状态
                "status":status
            }
            append_friend(data);
        }


        //关闭模态框
        $("#myModal").modal("hide");


    })

    function append_friend(data1) {
        $.ajax({
            url: basePath+"/demo1/friend/save",
            type: "post",
            //传入一个json字符串
            data: JSON.stringify(data1),
            //设置content-type,让后端可以用@RequestBody接收
            headers : {
                'Content-Type' : 'application/json;charset=utf-8'
            },
            //成功回调
            success: function (data) {

                //将好友放到侧边栏
                console.log(data)
                let friend = data.data.friend;
                let s;

                if (friend.status===1){
                    s='<div class="left-m">\n' +
                        '            <div class="left-d group" >'+friend.friendName+'</div>\n' +
                        '            <div class="right-d group">\n' +
                        '                <div>'+'群聊'+'</div>\n' +
                        '            </div>\n' +
                        '        </div>'
                }else {
                    s='<div class="left-m">\n' +
                        '            <div class="left-d" >'+friend.friendName+'</div>\n' +
                        '            <div class="right-d">\n' +
                        '                <div>'+friend.friendIp+'</div>\n' +
                        '            </div>\n' +
                        '        </div>'
                }
                $("#sidler").append(s);
                let elementById = document.getElementById("sidler");
                elementById.scrollTop=elementById.scrollHeight;
                //让侧边栏可以点击
                clickSidler();
                //清空表单
                let f = document.getElementById("friend");
                f.reset();

            }
        })
    }
    


    /*
    * 动态刷新
    *
    * */
    $(document).on("click","#refresh",function () {
        refresh();
    })

    function refresh() {
        $.ajax({
                "url": basePath+"/demo1/friend/get/"+user,
                type:'get',
                success:function (data){
                    //清空所有侧边栏
                    $("#sidler").children().remove();
                    //添加所有好友
                    let friends=data.data.friends;
                    console.log(friends)
                    for (let i=0;i<friends.length;i++){
                        let str;
                        let friend=friends[i];
                        if (friend.status===1){
                            str='<div class="left-m">\n' +
                                '            <div class="left-d group" >'+friend.friendName+'</div>\n' +
                                '            <div class="right-d group">\n' +
                                '                <div>'+'群聊'+'</div>\n' +
                                '            </div>\n' +
                                '        </div>'
                        }else {
                            str='<div class="left-m">\n' +
                                '            <div class="left-d" >'+friend.friendName+'</div>\n' +
                                '            <div class="right-d">\n' +
                                '                <div>'+friend.friendIp+'</div>\n' +
                                '            </div>\n' +
                                '        </div>'
                        }
                        $("#sidler").append(str);

                        clickSidler();

                    }
                }
            }
        )
    }


    //输入的用户名
    var input = document.getElementById("username");
    //主页对象
    let main = document.getElementById("main");
    //首页也对象
    var frt = document.getElementById("first");
    //当前对象
    var user;
    //发送对象
    var uuid;
    //当前聊天对象状态
    var status;
    //群聊名称
    var currentGroup;

    function first() {
        //获取输入框的值
        user = input.value;
        //使得主页面出现
        main.style.display = 'block';
        //让首页隐藏
        frt.style.display = 'none';
        // refresh();
        login(user);
        //让侧边栏可以点击
        clickSidler();
        //
    }
</script>
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script>
    // 成功发送
    var send_message=document.getElementById("chat_middle_item");
    // 发送内容
    var message=document.getElementById("chat_context_item");

    //将消息右边气泡加在右边
    function appendRight(user,time,ip,str) {
        //创建消息气泡
        var ans='<div class="chat_right_item_1 clearfix">'+user+'</div>'+
            '<div class="chat_right_item_2">'+
            '<div class="chat_right_time clearfix">'+time+'|'+ip+'</div>'+
            '<div class="chat_right_content clearfix">'+str+'</div>'
            +'</div>';
        var oLi=document.createElement("div");
        oLi.setAttribute("class","chat_right");
        oLi.innerHTML=ans;
        //放入主聊天框中
        send_message.append(oLi);
        //让滚轮每次置于最后
        send_message.scrollTop=send_message.scrollHeight;
        //发送后让输入框置于空
        message.value="";
    }

    //创建左边消息气泡
    function appendLeft(user, time, ip, str) {
        console.log("左边...")
        var ans='<div class="chat_left_item_1 clearfix">'+user+'</div>'+
            '<div class="chat_left_item_2">'+
            '<div class="chat_left_time clearfix">'+time+'|'+ip+'</div>'+
            '<div class="chat_left_content clearfix">'+str+'</div>'
            +'</div>';
        var oLi=document.createElement("div");
        oLi.setAttribute("class","chat_left");
        oLi.innerHTML=ans;
        send_message.append(oLi);
        send_message.scrollTop=send_message.scrollHeight;
        message.value="";
    }

    //webSocket变量
    var ws;

    //登录
    function login(user1) {
        if (!ws) {
            //获取到传来的用户
            var user = user1;
            try {
                //创建Websocket连接,ws开头的地址是后台Websocket服务器地址
                //returnCitySN["cip"]获取ip地址
                ws = new WebSocket("ws://127.0.0.1:8080/websocket/" + user+"/"+returnCitySN["cip"]);//连接服务器
                //socket打开事件
                ws.onopen = function (event) {
                    console.log("已经与服务器建立了连接...");
                    alert("登陆成功，可以开始聊天了")
                    //显示自己头像
                    let top = document.getElementById("top_middle");
                    top.innerHTML=user;
                    //document.getElementById("info").innerHTML += "<font size='4' color='red'>欢迎</font>"+user +"加入"+ "<br>";
                };
                //接收消息事件
                ws.onmessage = function (event) {

                    console.log(event)
                    //获取后台服务器传来的数据转换成json表达式
                    let data = eval("("+event.data+")");
                    var s="";
                    //如果是系统消息
                    if (data.user==='系统' && uuid===''){
                        //放入左边的消息气泡
                        appendLeft('系统',data.date,data.ip,data.message);
                    //    如果是自己发送消息,放入右边的消息气泡
                    }else if (data.user===user && data.message!=='add' &&data.message!=='yes_add'){
                        appendRight(data.user,data.date,data.ip,data.message);
                    //    如果是别人发送消息,放入左边的消息气泡
                    }else if (data.user===uuid && data.message!=='add' &&data.message!=='yes_add'){
                        appendLeft(data.user,data.date,data.ip,data.message);
                    //    如果在群聊里
                    }else if (uuid==='' && data.user!==' ' && data.message!==' '){
                        appendLeft(data.user,data.date,data.ip,data.message);
                    //    显示在线人数(系统消息)
                    }else if (data.user===' '&&data.message===' '){
                        let elementById = document.getElementById("top_right");
                        elementById.innerHTML=data.nums;
                    //    添加好友消息
                    }
                    if (data.message==='add'){
                        //如果是对方发送的是添加好友的消息才处理
                        if (data.uuid===user){
                            //确认是否同意添加该好友
                            if (confirm(data.user+"请求添加好友,您是否同意?")){
                                let data2 = {
                                    "mainName":user,
                                    "friendName":data.user,
                                    "friendIp":data.ip,
                                    "status":0
                                }
                                append_friend(data2)
                                //我确认同意了
                                var json12={}
                                json12.message='yes_add';
                                json12.user=user;
                                json12.uuid=data.user;
                                try {
                                    //向后台服务器发生消息
                                    ws.send(JSON.stringify(json12));
                                } catch (ex) {
                                    alert(ex.message);
                                }
                            }
                        }
                    //   监听到对方同意添加好友之后
                    }else if (data.message==='yes_add'){
                        if(data.uuid===user){
                            let data1 = {
                                "mainName":user,
                                "friendName":$("#friendname").val(),
                                "friendIp":$("#friendip").val(),
                                //当前的添加对象的状态
                                "status":status
                            }
                            append_friend(data1);
                        }
                    }

                };
                //关闭时间
                ws.onclose = function (event) {
                    alert("发生错误!")
                    console.log("已经与服务器断开连接...");
                };
                //发生错误事件
                ws.onerror = function (event) {
                    console.log("WebSocket异常！");
                };
            } catch (ex) {
                alert(ex.message);
            }
        } else {
            ws.close();
            ws = null;
        }
    }

    function SendData() {
        var data = message.value;
        //构建json对象
        var json={}
        json.message=data;
        json.user=user;
        json.uuid=uuid;
        try {
            //向后台服务器发生消息
            if (data!=null && data!==''){
                ws.send(JSON.stringify(json));
            }
        } catch (ex) {
            alert(ex.message);
        }
    }

    function clickSidler(){
        //实现侧边栏的导航
        //因为class属性相同,所以要用for循环
        for (const elementsByClassNameElement of document.getElementsByClassName("left-m")) {
            //遍历所有active属性,该属性标注的标签背景色为白色,先移除所有白色
            elementsByClassNameElement.onclick=function () {
                for (const active of document.getElementsByClassName("active")) {
                    active.classList.remove("active");
                }
                //将点击到的侧边栏标记为白色
                elementsByClassNameElement.classList.add("active");
                //遍历所有left-d属性的标签,取出其内容,设置到聊天框头标题里
                for (const elementsByClassNameElement1 of elementsByClassNameElement.getElementsByClassName("left-d")) {
                    let top = document.getElementById("top_left");
                    top.innerHTML=elementsByClassNameElement1.textContent;
                    //清楚聊天窗体内容
                    let lastElementChild = send_message.lastElementChild;
                    while (lastElementChild){
                        send_message.removeChild(lastElementChild);
                        lastElementChild=send_message.lastElementChild;
                    }
                    //点击和谁聊天
                    if (!elementsByClassNameElement1.classList.contains("group")){
                        uuid=elementsByClassNameElement1.textContent;
                    }else {
                        currentGroup=elementsByClassNameElement1.textContent;
                        //入群广播消息
                        uuid='';
                        var data = "<font size='4' color='red'>欢迎</font>"+user+"加入";
                        //构建json对象
                        var json={}
                        json.message=data;
                        json.uuid='';
                        json.user='系统'
                        try {
                            //向后台服务器发生消息
                            ws.send(JSON.stringify(json));
                        } catch (ex) {
                            alert(ex.message);
                        }
                    }
                }
            }
        }
    }



    //键盘事件
    document.getElementById("chat_context_item").onkeydown = function (e) {
        e = e || window.event;
        if(e.ctrlKey && e.keyCode == 13){
            SendData();
        }
    }


</script>

</body>
</html>
